package com.example.final_project.controller;

import com.example.final_project.entity.Order;
import com.example.final_project.entity.OrderDetail;
import com.example.final_project.service.OrderService;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpSession;

@Tag(name = "订单管理", description = "订单相关的API接口")
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Operation(summary = "获取订单列表页面", description = "返回订单列表页面")
    @GetMapping("/list")
    public String list(Model model,
                      @Parameter(description = "订单编号") @RequestParam(required = false) String orderNo,
                      @Parameter(description = "订单状态") @RequestParam(required = false) String status,
                      @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
                      @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
                      HttpSession session) {
        // 注入当前用户
        Object userObj = session.getAttribute("user");
        model.addAttribute("user", userObj);
        Long userId = null;
        Integer userStatus = null;
        if (userObj != null && userObj instanceof com.example.final_project.entity.User) {
            com.example.final_project.entity.User user = (com.example.final_project.entity.User) userObj;
            userStatus = user.getStatus();
            // 普通用户只查自己订单
            if (userStatus == null || userStatus != 1) {
                userId = user.getId();
            }
        }
        PageInfo<Order> pageInfo = orderService.getList(orderNo, userId, status, pageNum, pageSize);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("orderNo", orderNo);
        model.addAttribute("status", status);
        return "order/list";
    }

    @Operation(summary = "获取添加订单页面", description = "返回添加订单页面")
    @GetMapping("/add")
    public String add(HttpSession session, Model model) {
        Object userObj = session.getAttribute("user");
        model.addAttribute("user", userObj);
        return "order/add";
    }

    @Operation(summary = "添加订单", description = "添加新订单")
    @ApiResponse(responseCode = "200", description = "添加成功返回success，失败返回error")
    @PostMapping("/add")
    @ResponseBody
    public String add(@Parameter(description = "订单信息") @RequestBody Map<String, Object> params) {
        Order order = new Order();
        order.setUserId(Long.valueOf(params.get("userId").toString()));
        
        List<Map<String, Object>> details = (List<Map<String, Object>>) params.get("orderDetails");
        List<OrderDetail> orderDetails = details.stream().map(detail -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setBookId(Long.valueOf(detail.get("bookId").toString()));
            orderDetail.setQuantity(Integer.valueOf(detail.get("quantity").toString()));
            orderDetail.setPrice(new BigDecimal(detail.get("price").toString()));
            return orderDetail;
        }).collect(Collectors.toList());
        
        return orderService.create(order, orderDetails) ? "success" : "error";
    }

    @Operation(summary = "更新订单状态", description = "更新订单的状态")
    @ApiResponse(responseCode = "200", description = "更新成功返回success，失败返回error")
    @PostMapping("/updateStatus")
    @ResponseBody
    public String updateStatus(@Parameter(description = "订单状态信息") @RequestBody Map<String, Object> payload) {
        Long id = Long.valueOf(payload.get("id").toString());
        String status = payload.get("status").toString();
        return orderService.updateStatus(id, status) ? "success" : "error";
    }

    @Operation(summary = "支付订单", description = "将订单状态更新为已支付")
    @ApiResponse(responseCode = "200", description = "支付成功返回success，失败返回error")
    @PostMapping("/pay")
    @ResponseBody
    public String pay(@Parameter(description = "订单支付信息") @RequestBody Map<String, Object> payload) {
        Long id = Long.valueOf(payload.get("id").toString());
        return orderService.updateStatus(id, "PAID") ? "success" : "error";
    }

    @Operation(summary = "删除订单", description = "根据订单ID删除订单")
    @ApiResponse(responseCode = "200", description = "删除成功返回success，失败返回error")
    @PostMapping("/delete/{id}")
    @ResponseBody
    public String delete(@Parameter(description = "订单ID") @PathVariable Long id) {
        return orderService.delete(id) ? "success" : "error";
    }

    @Operation(summary = "获取订单详情", description = "根据订单ID获取订单详细信息")
    @ApiResponse(responseCode = "200", description = "成功获取订单详情")
    @GetMapping("/detail/{id}")
    @ResponseBody
    public Map<String, Object> detail(@Parameter(description = "订单ID") @PathVariable Long id) {
        Order order = orderService.getById(id);
        List<OrderDetail> orderDetails = orderService.getOrderDetailsByOrderId(id);
        Map<String, Object> result = new HashMap<>();
        result.put("orderInfo", order);
        result.put("orderDetails", orderDetails);
        return result;
    }

    @Operation(summary = "获取订单详情页面", description = "返回订单详情页面")
    @GetMapping("/detailPage/{id}")
    public String detailPage(@Parameter(description = "订单ID") @PathVariable Long id, Model model) {
        Order order = orderService.getById(id);
        List<OrderDetail> orderDetails = orderService.getOrderDetailsByOrderId(id);
        model.addAttribute("orderInfo", order);
        model.addAttribute("orderDetails", orderDetails);
        return "order/detail";
    }

    @Operation(summary = "获取订单列表API", description = "分页获取订单列表数据")
    @ApiResponse(responseCode = "200", description = "成功获取订单列表")
    @GetMapping("/api/list")
    @ResponseBody
    public Map<String, Object> apiList(
            @Parameter(description = "订单编号") @RequestParam(required = false) String orderNo,
            @Parameter(description = "订单状态") @RequestParam(required = false) String status,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            HttpSession session) {
        // 注入当前用户
        Object userObj = session.getAttribute("user");
        Long userId = null;
        Integer userStatus = null;
        if (userObj != null && userObj instanceof com.example.final_project.entity.User) {
            com.example.final_project.entity.User user = (com.example.final_project.entity.User) userObj;
            userStatus = user.getStatus();
            // 普通用户只查自己订单
            if (userStatus == null || userStatus != 1) {
                userId = user.getId();
            }
        }
        PageInfo<Order> pageInfo = orderService.getList(orderNo, userId, status, pageNum, pageSize);
        Map<String, Object> result = new HashMap<>();
        result.put("list", pageInfo.getList());
        result.put("total", pageInfo.getTotal());
        return result;
    }
} 